package com.heima.article.listen;

import com.heima.common.constants.article.ArticleConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 用于将监听到的行为数据
 * 存入到redis队列中 等待计算
 **/
@Component
@Slf4j
public class HotArticleScoreListener {

  @Autowired
  RedisTemplate<String, String> redisTemplate;


  @RabbitListener(queuesToDeclare = {@Queue(value = ArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE)})
  public void articleBehaviorHandler(@Payload String articleMess,
                                     Message message, Channel channel) {
    log.info( "文章实时更新队列: 接收到文章行为变化 消息内容: {}",articleMess);
    try {
    //1 接到信息
    //2 存到redis队列
      if (StringUtils.isNotBlank(articleMess)) {
        ListOperations<String, String> operations = redisTemplate.opsForList();
        operations.rightPush(ArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST, articleMess);
        // 手动确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    log.info("接收行为消息成功");
  }

}

